<?php

/**
 * 销量更新
 * File Name：SalesController.php
 * File Encoding：UTF-8
 * File New Time：2014-5-19 17:51:09
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class SalesController extends AdminBase {

    //批量更新销量
    public function actionIndex() {
        if (IS_POST) {
            $this->success('即将开始更新销量！', self::U('index', $_POST));
            exit;
        }
        $act = $_GET['act'];
        if ($act != 'start') {
            $this->render();
            exit;
        }
        //开始更新
        $model = GoodsModel::model();

        //查询条件
        $criteria = new CDbCriteria(array('order' => 'GoodsID DESC'));
        //当前处理id
        $current = $_GET['gid'];
        if ($current) {
            $criteria->addCondition("GoodsID < {$current}");
        }
        $start_time = strtotime($_GET['start_time']);
        $end_time = strtotime($_GET['end_time']);
        if ($start_time) {
            $criteria->addCondition("StartTime >= {$start_time}");
            if ($end_time) {
                $end_time = $end_time + 86400;
                $criteria->addCondition("StartTime <= {$end_time}");
            }
        } else {
            $start = time() - 86400 * 3;
            $end = time() + 86400 * 3;

            $criteria->addCondition("StartTime >= {$start} AND StartTime <= {$end}");
        }
        $_GET['count'] = $count = $_GET['count'] ? ((int) $_GET['count']) : $model->count($criteria);
        //每次处理
        $criteria->limit = 10;


        $data = $model->findAll($criteria);
        if (empty($data)) {
            $this->success('更新商品销量处理完毕！', self::U('index'));
            exit;
        } else {
            foreach ($data as $rs) {
                $_GET['gid'] = $rs->GoodsID;
                $sales = TaobaoApi::getInstance()->getSales($rs->ProductID);
                if ($sales) {
                    $rs->Sales = $sales;
                }
                $rs->save(false);
            }
        }
        //当前第几轮
        $_GET['i'] = $i = (int) $_GET['i'] ? ((int) $_GET['i'] + 1) : 1;
        //几轮
        $lun = ceil($count / $criteria->limit);
        //进度
        $jindu = round(($i / $lun) * 100, 3);
        $this->assign('waitSecond', 100);
        $this->suc("信息总数 <font color=\"#FF0000\">{$count}</font>，总共需要执行 <font color=\"#FF0000\">{$lun}</font> 次，当前第 <font color=\"#FF0000\">{$i}</font> 次，进度 <font color=\"#FF0000\">{$jindu}%</font>", self::U('index', $_GET));
    }

    //直接输出信息提示，不走日志
    protected function suc($message = '', $jumpUrl = '', $ajax = false) {
        $this->dispatchJump($message, 1, $jumpUrl, $ajax);
    }

}
